/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JPnlFirstPage.java
 *
 * Created on 04/11/2009, 21:42:38
 */
package systole.view.wizard.analysis;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import org.jdesktop.application.Action;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import systole.domain.signals.RawSignal;
import systole.domain.signals.Segment;
import systole.domain.signals.SignalFrequency;
import systole.exceptions.ExceptionDAO;
import systole.exceptions.ExceptionIO;
import systole.ioHandling.fileReaders.FileReaderTXT;
import systole.persistence.FacadeDB;
import systole.propertiesController.AnalysisWizardProperties;
import systole.propertiesController.SettingsProperties;
import systole.utils.ImageUtils;
import systole.view.crud.signalFrequency.ControllerSignalFrequencyEdition;
import systole.view.utils.ErrorDialog;

/**
 *
 * @author jmj
 */
public class JPnlFirstPage extends javax.swing.JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 5718279212595067946L;
    private File file = null;
    private RawSignal rawSignal = null;
    private AnalysisWizardProperties propertiesWizard;
    private SettingsProperties properties;

    /** Creates new form JPnlFirstPage */
    public JPnlFirstPage() {
        initComponents();
        this.jXImagePanel1.setImage(ImageUtils.buildImage(this, "resources/systole_96.png"));
        this.jXImagePanel1.revalidate();
        this.jXDatePicker.setEditable(true);
        this.jXDatePicker.setDate(Calendar.getInstance().getTime());
        this.properties = new SettingsProperties();
        this.propertiesWizard = new AnalysisWizardProperties();
        this.loadSignalFrequency();
        this.jChkInverted.setSelected(this.propertiesWizard.loadInvertedSignal());
        AutoCompleteDecorator.decorate(jCbPeriod);
    }

    private void loadSignalFrequency() {
        try {
            List<SignalFrequency> frecuencies = FacadeDB.getInstance().getSignalFrequencyBroker().getAllSignalFrequency();
            Iterator<SignalFrequency> it = frecuencies.iterator();
            this.jCbPeriod.removeAllItems();
            while (it.hasNext()) {
                this.jCbPeriod.addItem(it.next());
            }
            int lastIndex = this.propertiesWizard.loadSignalFrequencyUsed();
            if (this.jCbPeriod.getItemCount() > lastIndex) {
                this.jCbPeriod.setSelectedIndex(lastIndex);
            }
        } catch (ExceptionDAO ex) {
            FacadeDB.getInstance().refreshSession();
            ErrorDialog.showError(this, ex.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jBtnFile = new javax.swing.JButton();
        jLblWelcome = new javax.swing.JLabel();
        jLblFile = new javax.swing.JLabel();
        jEdtFile = new javax.swing.JTextField();
        jLblFileValid = new javax.swing.JLabel();
        jLblPeriod = new javax.swing.JLabel();
        jCbPeriod = new javax.swing.JComboBox();
        jBtnAddFrequency = new javax.swing.JButton();
        jXDatePicker = new org.jdesktop.swingx.JXDatePicker();
        jLblDate = new javax.swing.JLabel();
        jXImagePanel1 = new org.jdesktop.swingx.JXImagePanel();
        jChkInverted = new javax.swing.JCheckBox();

        setName("jPnlWelcome"); // NOI18N
        setPreferredSize(new java.awt.Dimension(370, 270));
        setRequestFocusEnabled(false);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(systole.view.SystoleApp.class).getContext().getResourceMap(JPnlFirstPage.class);
        jBtnFile.setIcon(resourceMap.getIcon("jBtnFile.icon")); // NOI18N
        jBtnFile.setText(resourceMap.getString("jBtnFile.text")); // NOI18N
        jBtnFile.setToolTipText(resourceMap.getString("jBtnFile.toolTipText")); // NOI18N
        jBtnFile.setName("jBtnFile"); // NOI18N
        jBtnFile.setPreferredSize(new java.awt.Dimension(28, 28));
        jBtnFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnFileActionPerformed(evt);
            }
        });

        jLblWelcome.setFont(jLblWelcome.getFont().deriveFont(jLblWelcome.getFont().getStyle() | java.awt.Font.BOLD, jLblWelcome.getFont().getSize()+2));
        jLblWelcome.setText(resourceMap.getString("jLblWelcome.text")); // NOI18N
        jLblWelcome.setName("jLblWelcome"); // NOI18N

        jLblFile.setText(resourceMap.getString("jLblFile.text")); // NOI18N
        jLblFile.setName("jLblFile"); // NOI18N

        jEdtFile.setEditable(false);
        jEdtFile.setText(resourceMap.getString("jEdtFile.text")); // NOI18N
        jEdtFile.setName("jEdtFile"); // NOI18N

        jLblFileValid.setText(resourceMap.getString("jLblFileValid.text")); // NOI18N
        jLblFileValid.setName("jLblFileValid"); // NOI18N

        jLblPeriod.setText(resourceMap.getString("jLblPeriod.text")); // NOI18N
        jLblPeriod.setName("jLblPeriod"); // NOI18N

        jCbPeriod.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", " " }));
        jCbPeriod.setToolTipText(resourceMap.getString("jCbPeriod.toolTipText")); // NOI18N
        jCbPeriod.setName("jCbPeriod"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(systole.view.SystoleApp.class).getContext().getActionMap(JPnlFirstPage.class, this);
        jBtnAddFrequency.setAction(actionMap.get("newPeriod")); // NOI18N
        jBtnAddFrequency.setIcon(resourceMap.getIcon("addEntity.icon")); // NOI18N
        jBtnAddFrequency.setText(resourceMap.getString("jBtnAddFrequency.text")); // NOI18N
        jBtnAddFrequency.setToolTipText(resourceMap.getString("jBtnAddFrequency.toolTipText")); // NOI18N
        jBtnAddFrequency.setName("jBtnAddFrequency"); // NOI18N
        jBtnAddFrequency.setPreferredSize(new java.awt.Dimension(28, 28));

        jXDatePicker.setToolTipText(resourceMap.getString("jXDatePicker.toolTipText")); // NOI18N
        jXDatePicker.setName("jXDatePicker"); // NOI18N

        jLblDate.setText(resourceMap.getString("jLblDate.text")); // NOI18N
        jLblDate.setName("jLblDate"); // NOI18N

        jXImagePanel1.setName("jXImagePanel1"); // NOI18N
        jXImagePanel1.setPreferredSize(new java.awt.Dimension(64, 64));

        javax.swing.GroupLayout jXImagePanel1Layout = new javax.swing.GroupLayout(jXImagePanel1);
        jXImagePanel1.setLayout(jXImagePanel1Layout);
        jXImagePanel1Layout.setHorizontalGroup(
            jXImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 92, Short.MAX_VALUE)
        );
        jXImagePanel1Layout.setVerticalGroup(
            jXImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 77, Short.MAX_VALUE)
        );

        jChkInverted.setText(resourceMap.getString("jChkInverted.text")); // NOI18N
        jChkInverted.setName("jChkInverted"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLblFileValid)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLblWelcome)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jEdtFile, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jBtnFile, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLblFile))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jXImagePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jChkInverted))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLblPeriod)
                            .addComponent(jLblDate)
                            .addComponent(jXDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jCbPeriod, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(jBtnAddFrequency, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(17, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLblFileValid))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jXImagePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLblWelcome)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLblFile)
                                .addGap(2, 2, 2)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                    .addComponent(jEdtFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jBtnFile, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jChkInverted)))))
                .addGap(18, 18, 18)
                .addComponent(jLblPeriod)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jCbPeriod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnAddFrequency, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLblDate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jXDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnFileActionPerformed
        this.file = this.open();
        if ((this.file != null)) {
            this.generateRawSignal();
        }
    }//GEN-LAST:event_jBtnFileActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnAddFrequency;
    private javax.swing.JButton jBtnFile;
    private javax.swing.JComboBox jCbPeriod;
    private javax.swing.JCheckBox jChkInverted;
    private javax.swing.JTextField jEdtFile;
    private javax.swing.JLabel jLblDate;
    private javax.swing.JLabel jLblFile;
    private javax.swing.JLabel jLblFileValid;
    private javax.swing.JLabel jLblPeriod;
    private javax.swing.JLabel jLblWelcome;
    private org.jdesktop.swingx.JXDatePicker jXDatePicker;
    private org.jdesktop.swingx.JXImagePanel jXImagePanel1;
    // End of variables declaration//GEN-END:variables

    /**
     * @return LblWelcome
     */
    public JLabel getjLblWelcome() {
        return jLblWelcome;
    }

    private File open() {
        File f = null;
        JFileChooser chooser = new JFileChooser(this.properties.loadImportSignalPath());
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            f = chooser.getSelectedFile();
        }
        return f;
    }

    /**
     * Action to add a new period
     */
    @Action
    public void newPeriod() {
        ControllerSignalFrequencyEdition controllerSignalFrequencyEdition = new ControllerSignalFrequencyEdition();
        controllerSignalFrequencyEdition.newEntity();
        this.loadSignalFrequency();
    }

    private void generateRawSignal() {
        if ((this.file != null) && (!this.file.getAbsolutePath().equals(this.jEdtFile.getText()))) {

            this.rawSignal = null;
            this.jEdtFile.setText("");

            FileReaderTXT reader = new FileReaderTXT();
            Segment segment = null;
            try {
                segment = reader.readFile(file);
                if (segment != null) {
                    this.rawSignal = new RawSignal();
                    this.getRawSignal().setSegment(segment);
                    this.jEdtFile.setText(this.file.getAbsolutePath());
                } else {
                    ErrorDialog.showError(this, "Archivo no válido");
                }
            } catch (ExceptionIO e) {
                ErrorDialog.showError(this, "Archivo no válido, " + e.getMessage());
            }
        }
    }

    private String validateFile() {
        if (this.getRawSignal() != null) {
            return null;
        }
        return ((this.jEdtFile.getText().isEmpty()) ? "Debe seleccionar un Archivo" : "Archivo no válido");
    }

    private String validatePeriod() {
        return ((this.jCbPeriod.getSelectedItem() == null) ? "Debe Seleccionar un período de muestro" : null);
    }

    private String validateDate() {
        return ((this.jXDatePicker.getDate() != null) ? null : "Debe ingresar una fecha");
    }

    /**
     * @return a string wit error message
     */
    public String validateConditions() {

        String result = this.validateFile();
        if (result != null) {
            return result;
        }

        result = this.validatePeriod();
        if (result != null) {
            return result;
        } else {
            this.propertiesWizard.saveSignalFrequencyUsed(this.jCbPeriod.getSelectedIndex());
        }

        this.propertiesWizard.saveInvertedSignal(this.jChkInverted.isSelected());

        result = this.validateDate();
        return result;
    }

    /**
     * @return the frequency
     */
    public SignalFrequency getFrequency() {
        return ((SignalFrequency) this.jCbPeriod.getSelectedItem());
    }

    /**
     * @return the rawSignal
     */
    public RawSignal getRawSignal() {
        return rawSignal;
    }

    /**
     * @return file name
     */
    public String getFileName() {
        return this.jEdtFile.getText();
    }

    /**
     * @return date
     */
    public Date getDate() {
        return this.jXDatePicker.getDate();
    }

    public String getCurrentFile() {
        return this.file.getName();
    }

    public boolean isInverted() {
        return this.jChkInverted.isSelected();
    }

    public void saveSettings() {
        this.propertiesWizard.saveProperties();
    }

    public void setSelectedRawSignal(RawSignal rs, String fileName) {
        this.rawSignal = rs;
        this.jEdtFile.setText(fileName);
        this.jChkInverted.setSelected(this.rawSignal.isInverted());
        this.file = new File(fileName);
    }
}
